//
//  BGLoginViewController.swift
//  Baga
//
//  Created by 飞王 on 16/12/30.
//  Copyright © 2016年 飞王. All rights reserved.
//

import UIKit
import HandyJSON
import Toast_Swift

let marginH = 40;
let marginV = 10;



class BGLoginViewController: UIViewController,UITextFieldDelegate {
    
//    private var: Bool; phoneNumberReady = ;
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white;
        setupNav();
        setupViews();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    private func setupNav() {
        title = "登录";
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(goBack));
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(goRegisterController));
        
    }
    
    private func setupViews() {
//        view.addSubview(userLoginLabel);
        view.addSubview(phoneTextFeild);
        view.addSubview(passwordTextFeild);
        view.addSubview(forgetPasswordButton);
        view.addSubview(loginButton);
        view.addSubview(logoText);
        view.addSubview(logoImageView);

        makeConstraints();
        
    }
    
    private func makeConstraints() {
//        userLoginLabel.snp.makeConstraints { (make) in
//            make.top.equalTo(view.snp.top).offset(20);
//            make.centerX.equalTo(view).offset(0);
//            make.left.equalTo(view);
//            make.right.equalTo(view);
//            make.height.equalTo(userLoginLabel.snp.width).multipliedBy(0.2);
//        }
        
        phoneTextFeild.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.top).offset(35);
            make.centerX.equalTo(view);
            make.left.equalTo(view).offset(marginH);
            make.right.equalTo(view).offset(-marginH);
            make.height.equalTo(phoneTextFeild.snp.width).multipliedBy(0.2);
            
        }
        
        passwordTextFeild.snp.makeConstraints { (make) in
            make.top.equalTo(phoneTextFeild.snp.bottom).offset(marginV);
            make.centerX.equalTo(view);
            make.left.equalTo(view).offset(marginH);
            make.right.equalTo(view).offset(-marginH);
            make.height.equalTo(passwordTextFeild.snp.width).multipliedBy(0.2);
        }
        
        forgetPasswordButton.snp.makeConstraints { (make) in
            make.top.equalTo(passwordTextFeild.snp.bottom).offset(marginV);
            make.right.equalTo(view).offset(-marginH);
            make.width.equalTo(100);
            make.height.equalTo(40);
        }
        
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(forgetPasswordButton.snp.bottom).offset(marginV);
            make.centerX.equalTo(view);
            make.left.equalTo(view).offset(marginH);
            make.right.equalTo(view).offset(-marginH);
            make.height.equalTo(passwordTextFeild.snp.width).multipliedBy(0.2);
        }
        
        logoText.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(marginV);
            make.centerX.equalTo(view);
            make.left.equalTo(view).offset(marginH);
            make.right.equalTo(view).offset(-marginH);
            make.height.equalTo(logoText.snp.width).multipliedBy(0.2);
        }
        
        logoImageView.snp.makeConstraints { (make) in
            make.top.equalTo(logoText.snp.bottom).offset(marginV);
            make.centerX.equalTo(view);
            make.width.equalTo(80);
            make.height.equalTo(logoImageView.snp.width);
        }
        
        
        
    }
    
    //MARK: - 业务逻辑
    
    //返回
    @objc private func goBack() {
        self.navigationController?.dismiss(animated: true, completion: {
        });
    }
    
    //注册
    @objc private func goRegisterController() {
        let registerController = BGRegisterViewController();
        self.navigationController?.pushViewController(registerController, animated: true);
    }
    
    //登录
    @objc private func loginToServer() {
        let loginParameters:Dictionary = [
            "userPhone":phoneTextFeild.text,
            "userPassword":passwordTextFeild.text
        ]
        
        
        
        BGNetworkTools.sharedTools.request(urlString: userLoginUrl, parameters: loginParameters as AnyObject?) { (respose, error) in
            
            //字典转对象
            let strJson = self.toJSONString(dict: respose as! NSDictionary?);
            
            
//            let jsonData = JSONSerializer.serialize(dict: (respose as! Dictionary));
//            let jsonString = String(data: jsonData as! Data, encoding: .utf8)
            
            print(strJson as Any)
            
            
            if let loginResponse: BGLoginResponse = JSONDeserializer<BGLoginResponse>.deserializeFrom(json: strJson) {
                
                if loginResponse.status == 1 {
                    //成功
                    self.dismiss(animated: true, completion: { 
                        
                    });
                } else {
                    //失败
                    self.passwordTextFeild.becomeFirstResponder();
                    
                }
                
                let keyWindow:UIWindow = ((UIApplication.shared.delegate?.window)!)!;
                keyWindow.makeToast(loginResponse.msg!);
                
                //使用toast提示
                print(loginResponse.msg as Any);
            }
            
            
        };
    }
    
    
    func toJSONString(dict:NSDictionary?)->String{
        
        let data = try? JSONSerialization.data(withJSONObject: dict!, options: JSONSerialization.WritingOptions.prettyPrinted)
        
        let strJson = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        
        return strJson! as String
        
    }
    
    //忘记密码
    

    // MARK: - LazyLoad
//    private lazy var userLoginLabel: UILabel = {
//        let userLoginLabel = UILabel();
//        userLoginLabel.text = "";
//        userLoginLabel.textColor = UIColor.orange;
//        userLoginLabel.font = UIFont(name: "", size: 20);
//        userLoginLabel.textAlignment = .center;
//        
//        return userLoginLabel;
//    }()
    
    private lazy var phoneTextFeild: BGUserInforTextField = {
        let phoneTextFeild = BGUserInforTextField(placeholderText: "手机号码", leftImageName: "zhuce_icon_shouji");
        phoneTextFeild.keyboardType = UIKeyboardType.numberPad;
        phoneTextFeild.delegate = self;
        return phoneTextFeild;
        
    }()
    
    private lazy var passwordTextFeild: BGUserInforTextField = {
        let passwordTextFeild = BGUserInforTextField(placeholderText: "请输入密码", leftImageName: "zhuce_icon_lock");
        passwordTextFeild.delegate = self;
//        passwordTextFeild.textContentType = .
        return passwordTextFeild;
        
    }()
    
    private lazy var forgetPasswordButton: UIButton = {
        let forgetPasswordButton = UIButton();
        forgetPasswordButton.setTitle("忘记密码", for: .normal);
        forgetPasswordButton.tintColor = UIColor.lightGray;
        
        
        return forgetPasswordButton;
    }()
    
    private lazy var loginButton: UIButton = {
        let loginButton = UIButton();
        loginButton.setTitle("登录", for: .normal);
        loginButton.tintColor = UIColor.white;
        loginButton.setBackgroundImage(UIImage(named:"zhuce_btn_d"), for: .disabled);
        loginButton.setBackgroundImage(UIImage(named:"zhuce_btn_h"), for: .normal);
        loginButton.isEnabled = false;
        loginButton.addTarget(self, action: #selector(loginToServer), for: .touchUpInside)
        
        return loginButton;
    }()
    
    private lazy var logoText: UILabel = {
        let logoText = UILabel();
        logoText.text = "一一一－－－新疆巴格网－－－一一一";
        logoText.textAlignment = NSTextAlignment.center;
        logoText.textColor = UIColor.gray;
        
        return logoText;
    }()
    
    private lazy var logoImageView:UIImageView = {
        let logoImageView = UIImageView(image: UIImage(named: "ico_logo_"));
        return logoImageView;
    }()
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.phoneTextFeild {
            if (textField.text?.lengthOfBytes(using: .utf8) == 11) {
                
                
                let phoneText:String = self.phoneTextFeild.text!;
                
                let index = phoneText.index(phoneText.startIndex, offsetBy: 1)
                
                let prefix = phoneText.substring(to: index)
                
                if (prefix.compare("1").rawValue == 0) {
                    //合法的
                    
                } else {
                    
                }
                
            } else {
                
            }
            
        } else if textField == self.passwordTextFeild{
            
        }
    }
}

extension BGLoginViewController {
}
